package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.enums.InnerAccountEnum;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.mapper.SysFlowMarketHistoryMapper;
import com.settlement.system.mapper.SysFlowMarketMapper;
import com.settlement.system.mapper.SysLazyToolUserMapper;
import com.settlement.system.model.entity.SysFlowMarket;
import com.settlement.system.model.entity.SysFlowMarketHistory;
import com.settlement.system.model.entity.SysLazyToolUser;
import com.settlement.system.model.form.SysFlowMarketForm;
import com.settlement.system.model.query.SysFlowMarketQuery;
import com.settlement.system.model.vo.NetAutoGroup;
import com.settlement.system.model.vo.NetAutoItem;
import com.settlement.system.model.vo.SysFlowMarketImportVo;
import com.settlement.system.service.SysDictService;
import com.settlement.system.service.SysFlowMarketService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 流程市场表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-12-28
 */
@Service
@RequiredArgsConstructor
public class SysFlowMarketServiceImpl extends ServiceImpl<SysFlowMarketMapper, SysFlowMarket> implements SysFlowMarketService {


    private final SysFlowMarketHistoryMapper sysFlowMarketHistoryMapper;

    private final SysLazyToolUserMapper sysLazyToolUserMapper;

    private final SysDictService sysDictService;

    @Override
    public Page<SysFlowMarket> getPage(SysFlowMarketQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        Page<SysFlowMarket> page = new Page<>(pageNum, pageSize);
        Page<SysFlowMarket> resultPage = this.baseMapper.getPage(page, queryParams);
        if (resultPage.getRecords().size() > 0) {
            List<Option> options = sysDictService.listDictOptions(SystemConstants.APP_CATEGORY);
            for (SysFlowMarket record : resultPage.getRecords()) {
                options.stream().filter(option -> option.getValue().equals(record.getType())).findFirst().ifPresent(option -> {
                    record.setTypeName(option.getLabel());
                });
            }
        }
        return resultPage;
    }

    @Override
    public boolean saveSysFlowMarket(SysFlowMarketForm sysFlowMarketForm) {
        SysFlowMarket sysFlowMarket =
                this.baseMapper.selectOne(new LambdaQueryWrapper<SysFlowMarket>().eq(SysFlowMarket::getType,
                        sysFlowMarketForm.getType()).eq(SysFlowMarket::getFlowName, sysFlowMarketForm.getFlowName()));
        if (sysFlowMarket == null) {
            sysFlowMarket = new SysFlowMarket();
            BeanUtil.copyProperties(sysFlowMarketForm, sysFlowMarket);
        } else {
            sysFlowMarket.setFileName(sysFlowMarketForm.getFileName());
            sysFlowMarket.setFilePath(sysFlowMarketForm.getFilePath());
            sysFlowMarket.setUpdateTime(LocalDateTime.now());
        }
        // 保存一份历史记录，方便后面回滚
        SysFlowMarketHistory history = new SysFlowMarketHistory();
        history.setFlowId(sysFlowMarket.getId());
        // 文件链接
        history.setFilePath(sysFlowMarket.getFilePath());
        // 文件大小
        history.setFileSize(sysFlowMarket.getFileSize());
        sysFlowMarketHistoryMapper.insert(history);
        // 保存脚本
        return this.saveOrUpdate(sysFlowMarket);

    }

    @Override
    public SysFlowMarketForm getSysFlowMarketFormData(Long id) {
        SysFlowMarket sysFlowMarket = this.getById(id);
        SysFlowMarketForm sysFlowMarketForm = new SysFlowMarketForm();
        BeanUtil.copyProperties(sysFlowMarket, sysFlowMarketForm);
        return sysFlowMarketForm;
    }

    @Override
    public boolean deleteSysFlowMarket(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysFlowMarketImportVo> voList) {
        List<SysFlowMarket> sysFlowMarketList = new ArrayList<>();
        for (SysFlowMarketImportVo importVo : voList) {
            SysFlowMarket sysFlowMarket = new SysFlowMarket();
            BeanUtil.copyProperties(importVo, sysFlowMarket);
            sysFlowMarketList.add(sysFlowMarket);
        }
        this.saveOrUpdateBatch(sysFlowMarketList);
    }

    @Override
    public List<SysFlowMarketImportVo> findByIds(String idsStr) {
        if (StrUtil.isBlank(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysFlowMarket> sysFlowMarketList = this.getBaseMapper().selectBatchIds(ids);
        List<SysFlowMarketImportVo> voList = new ArrayList<>();
        for (SysFlowMarket sysFlowMarket : sysFlowMarketList) {
            SysFlowMarketImportVo vo = new SysFlowMarketImportVo();
            BeanUtil.copyProperties(sysFlowMarket, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public List<String> categoryList() {
        List<SysFlowMarket> flowMarkets = this.list();
        List<String> typeNameList = new ArrayList<>();
        for (SysFlowMarket flowMarket : flowMarkets) {
            if (!typeNameList.contains(flowMarket.getType())) {
                typeNameList.add(flowMarket.getType());
            }
        }
        return typeNameList;
    }

    @Override
    public List<SysFlowMarket> flowListByType(String type) {
        return this.list(new LambdaQueryWrapper<SysFlowMarket>().eq(SysFlowMarket::getType, type));
    }

    @Override
    public boolean publish(Long flowId, String type, String content) {
        SysFlowMarket sysFlowMarket = this.baseMapper.selectById(flowId);
        SysFlowMarket publishMarket =
                this.baseMapper.selectOne(new LambdaQueryWrapper<SysFlowMarket>().eq(SysFlowMarket::getType,
                        type).eq(SysFlowMarket::getFlowName, sysFlowMarket.getFlowName()));
        if (publishMarket == null) {
            publishMarket = new SysFlowMarket();
            BeanUtil.copyProperties(sysFlowMarket, publishMarket);
            publishMarket.setType(type);
            publishMarket.setCreateTime(LocalDateTime.now());
            publishMarket.setUpdateTime(null);
        } else {
            // 更新脚本链接即可
            publishMarket.setFilePath(sysFlowMarket.getFilePath());
            // 保存一份历史记录，方便后面回滚
            SysFlowMarketHistory history = new SysFlowMarketHistory();
            history.setFlowId(publishMarket.getId());
            // 文件链接
            history.setFilePath(publishMarket.getFilePath());
            // 文件大小
            history.setFileSize(publishMarket.getFileSize());
            sysFlowMarketHistoryMapper.insert(history);
        }
        publishMarket.setContent(content);
        // 保存脚本
        return this.saveOrUpdate(publishMarket);
    }

    @Override
    public String downloadFlow(Long flowId) {
        SysFlowMarket sysFlowMarket = this.baseMapper.selectById(flowId);
        return sysFlowMarket.getFilePath();
    }

    @Override
    public List<NetAutoGroup> getAllFlowList() {
        List<NetAutoGroup> groups = new ArrayList<>();
        List<SysFlowMarket> sysFlowMarkets = this.list();
        List<Option> options = sysDictService.listDictOptions(SystemConstants.APP_CATEGORY);
        // 按照类型分类
        Map<String, List<SysFlowMarket>> groupList = sysFlowMarkets.stream().collect(Collectors.groupingBy(SysFlowMarket::getType));
        Set<String> typeList = groupList.keySet();
        NetAutoGroup group;
        List<SysFlowMarket> items;
        NetAutoItem item;
        Option option;
        for (String type : typeList) {
            group = new NetAutoGroup();
            option = options.stream().filter(op -> op.getValue().equals(type))
                    .findFirst()
                    .orElse(null);
            if (option != null) {
                group.setTitle(option.getLabel());
            }
            items = groupList.get(type);
            for (SysFlowMarket sysFlowMarket : items) {
                item = new NetAutoItem();
                item.setId(sysFlowMarket.getId().intValue());
                item.setTitle(sysFlowMarket.getFlowName());
                item.setUrl(sysFlowMarket.getFileName());
                item.setSize("%skb".formatted(sysFlowMarket.getFileSize().setScale(2, RoundingMode.HALF_UP)));
                if (StringUtils.isNotEmpty(sysFlowMarket.getContent())) {
                    item.setContent(sysFlowMarket.getContent());
                } else {
                    item.setContent("暂无内容");
                }
                group.getItems().add(item);
            }
            groups.add(group);
        }
        return groups;
    }

    @Override
    public List<NetAutoGroup> getUserFlowList(String mobile) {
        List<NetAutoGroup> groups = new ArrayList<>();
        List<SysFlowMarket> sysFlowMarkets = this.list();
        List<Option> options = sysDictService.listDictOptions(SystemConstants.APP_CATEGORY);
        // 按照类型分类，普通用户过滤那些测试的脚本
        Map<String, List<SysFlowMarket>> groupList;
        SysLazyToolUser sysLazyToolUser = null;
        if(StringUtils.isMobile(mobile)){
            sysLazyToolUser = sysLazyToolUserMapper.selectOne(new LambdaQueryWrapper<SysLazyToolUser>().eq(SysLazyToolUser::getMobile,
                    mobile));
        }
        if(sysLazyToolUser != null && InnerAccountEnum.Y.getValue().equals(sysLazyToolUser.getInnerStatus())){
            groupList = sysFlowMarkets.stream().collect(Collectors.groupingBy(SysFlowMarket::getType));
        }else{
            groupList = sysFlowMarkets.stream().filter(sysFlowMarket -> !SystemConstants.TEST_CATEGORY.equals(sysFlowMarket.getType())).collect(Collectors.groupingBy(SysFlowMarket::getType));
        }
        Set<String> typeList = groupList.keySet();
        NetAutoGroup group;
        List<SysFlowMarket> items;
        NetAutoItem item;
        Option option;
        for (String type : typeList) {
            group = new NetAutoGroup();
            option = options.stream().filter(op -> op.getValue().equals(type))
                    .findFirst()
                    .orElse(null);
            if (option != null) {
                group.setTitle(option.getLabel());
            }
            items = groupList.get(type);
            for (SysFlowMarket sysFlowMarket : items) {
                item = new NetAutoItem();
                item.setId(sysFlowMarket.getId().intValue());
                item.setTitle(sysFlowMarket.getFlowName());
                item.setUrl(sysFlowMarket.getFileName());
                item.setSize("%skb".formatted(sysFlowMarket.getFileSize().setScale(2, RoundingMode.HALF_UP)));
                if (StringUtils.isNotEmpty(sysFlowMarket.getContent())) {
                    item.setContent(sysFlowMarket.getContent());
                } else {
                    item.setContent("暂无内容");
                }
                group.getItems().add(item);
            }
            groups.add(group);
        }
        return groups;
    }

    @Override
    public String getFilePathByName(String fileName) {
        SysFlowMarket sysFlowMarket =
                this.baseMapper.selectOne(new LambdaQueryWrapper<SysFlowMarket>().eq(SysFlowMarket::getFlowName, fileName));
        if(sysFlowMarket != null){
            return sysFlowMarket.getFileName();
        }
        return null;
    }
}
